<template>
  <div style="display: flex; flex-direction: column; width: 100%;">
    <div v-if="data.showOption" style="display: flex;">
      <div style="background-color: #409eff;display: flex;padding: 5px;width: 16%;border-radius: 5px;height: 25px;">
        <span @click="loadHistoricalConversation"
              style="color: white;
            display: flex;
            align-items: center;
            cursor: pointer;
          ">
        <el-icon><Stopwatch/></el-icon>
        历史会话
      </span>
        <span style="margin: 0 10px;color: white">|</span>
        <span @click="addConversation"
              style="color: white;
            display: flex;
            align-items: center;
            cursor: pointer;
          ">
        <el-icon><CirclePlus/></el-icon>
        新建会话
      </span>
      </div>
      <div style="flex-grow: 1; display: flex; justify-content: center;margin-right: 10%">
        <el-dropdown>
        <span class="el-dropdown-link">
          {{ data.conversionTitle }}
          <el-icon class="el-icon--right"><ArrowDown/></el-icon>
        </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="reName(data.conversionTitle)">
                <el-icon>
                  <EditPen/>
                </el-icon>
                重命名
              </el-dropdown-item>
              <el-dropdown-item @click="deleteConversion">
                <el-icon>
                  <Delete/>
                </el-icon>
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div @click="clickCloseBold" v-else
         style="background-color: red;
         padding: 5px;
         width: 25px;
         height: 25px;
         color: white;
         display: flex;
         align-items: center;
         justify-content: center;
         border-radius: 5px;
         cursor: pointer">
      <el-icon>
        <CloseBold/>
      </el-icon>
    </div>

    <div v-if="data.showConversation"
         style="height: 80%;
         width: 101%;
         /*border: 1px solid blue;*/
         padding-left: 30px;
         overflow-y: auto;
         box-sizing: border-box;
         margin-top: 10px">
      <!--       显示响应结果-->
      <div v-if="data.showConversation"
           ref="scrollBox"
           style="overflow-y: auto;display: flex;flex-direction:column;
           /*border: 1px solid blue;*/
         height: 100%;width: 100%;">
        <div v-for="(item,index) in data.contentsData" :key="index">
          <pre v-if="item.senderId === data.robotId" style="display: flex;flex-direction: row;margin: 5px 0">
            <el-avatar style="" :src="data.robotAvatar"/>
            <div style="background-color: #f3f5fc;
                  border-radius: 5px;padding: 10px;
                  margin-left: 5px;max-width: 88%;">{{ item.content }}</div>
          </pre>
          <pre v-else style="display: flex;flex-direction: row;justify-content: flex-end;margin: 5px 0">
                  <div style="background-color: #f3f5fc;
                  border-radius: 5px;padding: 10px;
                  margin-right: 5px;max-width: 88%;">{{ item.content }}</div>
            <el-avatar style="margin: 0 30px 0 0" :src="userData.avatar"/>
          </pre>
        </div>
      </div>
    </div>


    <div v-if="data.showConversation"
         style="width: 100%; display: flex; justify-content: center; align-items: center;margin-top: 2%">
      <el-input
          style="width: 90%; margin-right: 10px;"
          v-model="userQuestion"
          placeholder="请输入您的问题..."
          @keyup.enter="askMoonshot"
      />
      <el-button type="primary" @click="askMoonshot">提问</el-button>
    </div>


    <div v-if="data.showHistoricalConversation"
         style="height: 80%; width: 100%; padding:0 30px;box-sizing: border-box;margin-top: 10px;">
      <div style="height: 50px;line-height: 50px;font-size: 30px;text-align: center">
        <div>历史会话</div>
      </div>
      <div v-for="item in data.historicalConversations">
        <div @click="gotoConversion(item.conversationId)"
             @mouseenter="item.showOption = true;"
             @mouseleave="item.showOption = false"
             style="background-color: #f3f5fc;padding: 10px;border-radius: 5px;margin: 5px 0;display: flex;justify-content: space-between;cursor: pointer">
          <div>{{ item.title }}</div>
          <div v-if="!item.showOption">
            {{ item.createTime }}
          </div>
          <div v-if="item.showOption" style="display: flex;">
            <div @click.stop="reHistoricalName(item.title,item.conversationId)"
                 style="margin-right: 5px;cursor: pointer">
              <el-icon>
                <EditPen/>
              </el-icon>
              修改
            </div>
            <div @click.stop="deleteHistoricalConversion(item.conversationId)" style="cursor: pointer">
              <el-icon>
                <Delete/>
              </el-icon>
              删除
            </div>
          </div>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup>
import {onMounted, onUpdated, reactive, ref} from 'vue';
import fetchMoonshotCompletion from '@/utils/moonshot.js';
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus';
import {ArrowDown, CirclePlus, CloseBold, Delete, EditPen, Stopwatch} from '@element-plus/icons-vue'
import request from "../utils/request.js";
import {useRoute} from "vue-router";

const route = useRoute();

const dataString = localStorage.getItem('data');
// 通过JSON.parse转换字符串为对象
const userData = dataString ? JSON.parse(dataString) : null;
console.log("用户信息：", userData)

// 定义状态变量
const userQuestion = ref('');
const responseMessage = ref('');
let loadingInstance = null;


const scrollBox = ref(null);


onUpdated(() => {
  // 确保添加内容后视图滚动到底部
  if (scrollBox.value) {
    scrollBox.value.scrollTop = scrollBox.value.scrollHeight;
  }
});


onMounted(() => {
  // 使用队列微任务确保DOM已更新
  queueMicrotask(() => {
    // 确保scrollBox被引用并且现在已经存在DOM中
    if (scrollBox.value) {
      // 将滚动条设置到最底部
      scrollBox.value.scrollTop = scrollBox.value.scrollHeight;
    }
  });
});

const data = reactive({
  showOption: true,
  showConversation: true,
  showHistoricalConversation: false,
  newConversation: false,
  historicalConversations: null,
  contentsData: null,
  currentConversationId: route.query.ConversationId,
  conversionTitle: null,
  allConversationIds: [],
  preDeleteHistoricalConversationId: null,//删除的前一个历史会话ID
  robotAvatar: null,
  robotId: null,
})



const askMoonshot = async () => {
  try {
    // 开始请求，显示加载提示
    loadingInstance = ElLoading.service({
      lock: true,
      text: '正在思考中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)',
    });


    const messages = [
      {role: "system", content: "你的名字叫Kitty，身份是招投标文件管理系统的人工智能助手..."},
      {
        role: "system", content: "你务必知道这个系统的功能：1、能建立各行业招标文件规范，形成招标规范库，实现标书规范知识分享。2、能实现自动分析并提取招标文件要素功能，便于指导投标文件有针对性编写，提高工作效率。3、能实现自动匹配分析招标文件与投标文件，产生匹配分析报告，提高文件编写正确率，减少标书被废风险4、能实现招投标文件的管理功能，用户能对自己的文件进行搜索、上传、下载、更新和删除功能。"
      },
      {
        role: "system", content: "你的回复每行不得超过80个字符，超过后要换行"
      },
    ];

    // 遍历 data.contentsData
    data.contentsData.forEach((item) => {
      // 创建新的系统消息对象，并添加到 updatedMessages 数组中
      if (item.senderId !== data.robotId) {
        messages.push({
          role: "system",
          content: "我的提问：" + item.content
        });
      } else {
        messages.push({
          role: "system",
          content: "你的回答：" + item.content
        });
      }
    });

    messages.push({
      role: "user",
      content: userQuestion.value
    });


    const completion = await fetchMoonshotCompletion(messages);
    console.log(completion);

    if (completion) {
      responseMessage.value = completion.choices[0].message.content;

      const QuestionContentEntity = {
        content: userQuestion.value,
        senderId: userData.userId,
        recipientId: data.robotId,
        conversationId: data.currentConversationId,
      }

      request.post(`/java/content/push`, QuestionContentEntity).then((res) => {
        console.log(res)
        if (res.code === 200) {
          const answerContentEntity = {
            content: responseMessage.value,
            senderId: data.robotId,
            recipientId: userData.userId,
            conversationId: data.currentConversationId,
          }
          request.post(`/java/content/push`, answerContentEntity).then((res) => {
            Load()
          })
        }
      })

    } else {
      ElMessage.info("响应失败")
    }

  } catch (error) {
    console.error("无法从Moonshot API获取:", error);
    responseMessage.value = error.message;
  } finally {
    // 请求完成后关闭加载提示
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};


//历史会话
const loadHistoricalConversation = () => {
  data.showHistoricalConversation = true;
  data.showConversation = false;
  data.showOption = false;

  request.get(`/java/conversation/conversations/${userData.userId}`).then((res) => {
    // 按照 createTime 属性由晚到早排序
    data.historicalConversations = res.data.sort((a, b) => {
      return new Date(b.createTime) - new Date(a.createTime);
    });
  })
}

const clickCloseBold = () => {
  data.showOption = true;
  data.showConversation = true;
  data.showHistoricalConversation = false;

  if (data.currentConversationId === data.preDeleteHistoricalConversationId) {
    location.href = '/assistant'
  }
}

const addConversation = () => {
  newConversation();
}

const newConversation = () => {
  const id = Math.floor(Math.random() * 1000000000);
  const entity = {
    conversationId: id.valueOf(),
    title: null,
    userId: userData.userId,
    createTime: null,
    isDeleted: null,
  }
  request.post(`/java/conversation/push`, entity).then((res) => {
    console.log(res)
  })
  location.href = '/assistant?ConversationId=' + entity.conversationId;
  data.currentConversationId.value = entity.conversationId;
}

const Load = () => {
  request.get(`/user/getRobot`).then((res) => {
    console.log("机器人头像：", res)
    data.robotAvatar = res.data.avatar;
    data.robotId = res.data.userId;
  })


  if (data.currentConversationId === undefined) {
    request.get(`/java/conversation/conversations/${userData.userId}`).then((res) => {
      console.log("查询会话记录", res)
      if (res.data.length === 0) {
        newConversation();
        return;
      }
      const lastIndex = res.data.length - 1;
      data.currentConversationId = res.data[lastIndex].conversationId;
      data.conversionTitle = res.data[lastIndex].title;
      // 将所有的 conversationId 存储下来
      data.allConversationIds = res.data.map(conversation => conversation.conversationId);
      request.get(`/java/content/getContent/${data.currentConversationId}`).then((res) => {
        console.log(res)
        data.contentsData = res.data;
        // data.contentsData = res.data.map((item) => {
        //   return {
        //     ...item,
        //     content: item.content.replace(/(\d+)\./g, "\n$1.").replace(/(\d+)[。]/g, "$1。\n"),
        //     showOption: false // 添加新属性 showOption 并设置为 false
        //   };
        // });
      })
    })
  } else {
    request.get(`/java/content/getContent/${data.currentConversationId}`).then((res) => {
      console.log(res)
      data.contentsData = res.data.map((item) => {
        return {
          ...item,
          content: item.content.replace(/(\d+)\./g, "\n$1.").replace(/(\d+)[。]/g, "$1。\n"),
          showOption: false // 添加新属性 showOption 并设置为 false
        };
      });

      userQuestion.value = ""

      request.get(`/java/conversation/detail/${data.currentConversationId}`).then((res) => {
        data.conversionTitle = res.data.title;
      })

    })
  }


}


Load();


const gotoConversion = (conversationId) => {
  data.currentConversationId = conversationId;
  location.href = '/assistant?ConversationId=' + conversationId;
}

const reName = (title) => {
  ElMessageBox.prompt('请输入修改的名称', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: title // 将输入框的初始值设为 title
  })
      .then(({value}) => {
        const editData = {
          conversationId: data.currentConversationId,
          title: value,
        }

        request.put(`/java/conversation/edit`, editData).then((res) => {
          console.log(res)
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: `修改成功`,
            })
            Load();
          } else {
            ElMessage({
              type: 'info',
              message: `修改失败`,
            })
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消修改',
        })
      })
}


const reHistoricalName = (title, conversationId) => {
  ElMessageBox.prompt('请输入修改的名称', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: title // 将输入框的初始值设为 title
  })
      .then(({value}) => {
        const editData = {
          conversationId: conversationId,
          title: value,
        }

        request.put(`/java/conversation/edit`, editData).then((res) => {
          console.log(res)
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: `修改成功${value}`,
            })
            loadHistoricalConversation();
          } else {
            ElMessage({
              type: 'info',
              message: `修改失败`,
            })
          }
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消修改',
        })
      })
}

const deleteHistoricalConversion = (conversationId) => {
  data.currentConversationId = conversationId;
  ElMessageBox.confirm(
      '确认删除吗?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        const conversationIds = [];
        conversationIds.push(data.currentConversationId);
        request.delete(`/java/conversation/delete/${conversationIds}`).then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: `删除成功`,
            })

            // 找到要删除的 conversationId 在 allConversationIds 中的索引
            const index = data.allConversationIds.indexOf(conversationId);
            if (index !== -1) {
              // 如果找到了，就从 allConversationIds 中移除该 conversationId
              data.allConversationIds.splice(index, 1);
            }

            data.preDeleteHistoricalConversationId = conversationId

            loadHistoricalConversation();
          }else {
            ElMessage({
              type: 'info',
              message: '删除失败',
            })
          }
        })

      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      })
}

const deleteConversion = () => {
  ElMessageBox.confirm(
      '确认删除吗?',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        const conversationIds = [];
        conversationIds.push(data.currentConversationId);
        request.delete(`/java/conversation/delete/${conversationIds}`).then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: `删除成功`,
            })

            location.href = '/assistant'
          }else {
            ElMessage({
              type: 'info',
              message: '删除失败',
            })
          }
        })

      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      })
}

</script>


<style scoped>
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>